<template>
	<view>
		<w-picker  mode="date"  startYear="1970"  endYear="2030" :defaultVal="[0,1,3]"  :current="true"  @confirm="onConfirmbirthday"  ref="date"  themeColor="#f00" ></w-picker>
		<w-picker  mode="region" :defaultVal="[15,0]"  @confirm="onConfirmcity"  ref="region"  themeColor="#E02E24" ></w-picker>
		<view class="uni-padding-wrap">
			<form @submit="formSubmit"  >
				<view class="un-touxiang">
					<view class="portrait-box" >
						<image class="portrait" :src=" imageSrc[0]||avator|| '/static/missing-face.png'" mode="aspectFill"></image>
					</view>
					<text class="un-touxiang-text" @tap="changetouxiang" >点击修改头像</text>
					<min-action-sheet ref="as"></min-action-sheet>
				</view>
				
				<view class="cu-form-group " style="margin-top: 25upx;">
					<view class="title">用户ID</view>
					<input name="userid" disabled="true" v-model="userid"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">昵称</view>
					<input placeholder="请输入昵称" name="nickname" v-model="nickname"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">性别</view>
					<radio-group class="uni-flex" name="gender" v-model="gender">
						<label>
							<radio value=1 color="#E02E24" style="transform:scale(0.8)" :checked="this.gender===1" />男</label>
						<label style="margin-left: 101upx;">
							<radio value=2 color="#E02E24" style="transform:scale(0.8)" :checked="this.gender===2"/>女</label>
					</radio-group>
				</view>
				
				<view class="cu-form-group">
					<view class="title">生日</view>
					<input placeholder="请选择生日" name="birthdayValue" :value="birthdayValue?birthdayValue:''" @tap="showbirthday"></input>
					<text class="yticon icon-you"></text>
				</view>
				<view class="cu-form-group">
					<view class="title">城市</view>
					<input placeholder="请选择城市" name="cityValue" :value="cityValue?cityValue:''" @tap="showcity"></input>
					<text class="yticon icon-you"></text>
				</view>
				<view class="cu-form-group">
					<view class="title">职业</view>
					<input placeholder="请填写职业" name="job" :value="job?job:''"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">个性签名</view>
					<input placeholder="请填写你的个性签名" name="introduce" :value="introduce?introduce:''"></input>
				</view>
				
				<view class="un-fentext">
					<text>喜欢的分类</text>
				</view>
			
				<view class="un-fenlei">
					<checkbox-group @change="checkboxChange" >
					  <label  style="display: inline-flex"  @click="labelBtn(item.value,index)" v-for="(item,index) in categorylist" :key="item.value">
						<view :class="item.checked ?  'checkbox selectBox' : 'checkbox'">
							<checkbox :value="item.value" color="#E02E24" :checked="item.checked" v-show="false"/>{{item.name}}
						</view> 
					  </label>
					</checkbox-group>
				</view>
				
				
				<view class="uni-btn-v uni-common-mt un-ti" >
					<button style="background-color: #E02E24;" class="btn-submit" formType="submit" type="primary">提交</button>
				</view>
			</form>
		</view>
	</view> 
</template>

<script>
	
	//来自 graceUI 的表单验证， 使用说明见手册 http://grace.hcoder.net/doc/info/73-3.html
	var  graceChecker = require("../../../common/graceChecker.js");
	import { mapState } from 'vuex'; 
	import wPicker from "@/components/w-picker/w-picker.vue";
	import minActionSheet from '@/components/min-action-sheet/min-action-sheet';
	export default {
		components:{
				wPicker,
				minActionSheet
		},
		data() {
			return {
				avator:'',//原头像
				imageSrc: [],//头像数组
				cityValue:'',//城市
				birthdayValue:'',//生日
				mode:'',//选择框类型
				labelName:'',//分类值
				labelDataList:'',//分类选择结果
				categorylist:[],//分类集合
				show:false,
				
				userid:'',//用户ID
				nickname:'',//name
				gender:'',//性别
				job:'',//工作
				introduce:'',//个性签名
			}
		},
		onUnload() {
			this.imageSrc = [];
		},
		computed: {
			...mapState(['hasLogin','userInfo'])
		},
		onLoad() {
			this.loadData();
			uni.startPullDownRefresh();
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			//用户信息回显
			async loadData(){
				this.$http.post("/user/info",{
					SIGNATURE:uni.getStorageSync("SIGNATURE"),
					TOKEN:uni.getStorageSync('userInfo').TOKEN,
				}).then(res=>{
					
					if(res.data.STATE==='0' && res.statusCode===200){
						const user=res.data.OBJECT;
						this.userid=user.ID;
						this.nickname=user.NAME;
						this.gender=user.SEX;
						if(user.BIRTHDAY&&user.BIRTHDAY.length>0){
							this.birthdayValue=user.BIRTHDAY.substring(0,10);
						}
						this.cityValue=user.CITY;
						this.job=user.JOB;
						this.introduce=user.INTRODUCE;
						if (user.LOVECATE) {
							this.labelDataList=user.LOVECATE.split(',');
						}
						if(user.AVATOR){
							this.avator=getApp().globalData.imageAddress+user.AVATOR;
						}
					}
				}).catch(err=>{
					console.log('request fail',err);
				})
				

				this.$http.post("/goods/findCategory",{
					SIGNATURE:uni.getStorageSync("SIGNATURE"),
					TOKEN:uni.getStorageSync('userInfo').TOKEN,
				}).then(res=>{
					if(res.data.STATE==='0' && res.statusCode===200){
						res.data.OBJECT.THREE.map(item=>{
							let cate={};
							cate.name=item.CATEGORYNAME;
							cate.value=item.CATEGORYID+"";
							if(this.labelDataList.indexOf(cate.value) >-1){
								cate.checked=true;
							}else{
								cate.checked=false;
							}
							this.categorylist.push(cate);
						}) 
					}
				}).catch(err=>{
					console.log('request fail',err);
				})
			},
			
			formSubmit: function (e) {
				
				//将下列代码加入到对应的检查位置
				//定义表单规则
				var rule = [
					{name:"nickname", checkType : "string", checkRule:"1,6",  errorMsg:"昵称应为1-6个字符"}
				];
				//进行表单检查
				var formData = e.detail.value;
				var checkRes = graceChecker.check(formData, rule);
				if(checkRes){
					if (this.imageSrc.length>0) {
						this.imageSrc.forEach(item=>{
							uni.uploadFile({
								url: getApp().globalData.http+'/user/fileUpload2?SIGNATURE='+
								uni.getStorageSync("SIGNATURE"),
								filePath: item,
								fileType: 'image',
								name: 'data',
								success: (res) => {
									console.log('uploadImage success, res is:', res)
									let avator=JSON.parse(res.data);
									this.$http.post("/user/update",{
										SIGNATURE:uni.getStorageSync("SIGNATURE"),
										TOKEN:uni.getStorageSync('userInfo').TOKEN,
										NICKNAME:formData.nickname,
										SEX:formData.gender,
										BIRTHDAY:formData.birthdayValue,
										CITY:formData.cityValue,
										JOB:formData.job,
										INTRODUCE:formData.introduce,
										LOVECATE:this.labelDataList,
										AVATOR:avator.OBJECT,
									}).then(res1=>{
										if(res1.data.STATE == '903'||res1.data.STATE == '904'){
											uni.navigateTo({
												url:'/pages/public/login1'
											})
										}
										if(res1.data.STATE==='0' && res1.statusCode===200){
											uni.showToast({title:"修改成功!", icon:"none"});
											uni.navigateBack({
												
											})
										}
									}).catch(err=>{
										console.log('request fail',err);
									})
								},
								fail: (err) => {
									console.log('uploadImage fail', err);
									uni.showModal({
										content: err.errMsg,
										showCancel: false
									});
								}
							});
						})
					}else{
						this.$http.post("/user/update",{
							SIGNATURE:uni.getStorageSync("SIGNATURE"),
							TOKEN:uni.getStorageSync('userInfo').TOKEN,
							NICKNAME:formData.nickname,
							SEX:formData.gender,
							BIRTHDAY:formData.birthdayValue,
							CITY:formData.cityValue,
							JOB:formData.job,
							INTRODUCE:formData.introduce,
							LOVECATE:this.labelDataList,
						}).then(res1=>{
							if(res1.data.STATE == '903'||res1.data.STATE == '904'){
								uni.navigateTo({
									url:'/pages/public/login1'
								})
							}
							if(res1.data.STATE==='0' && res1.statusCode===200){
								uni.showToast({title:"修改成功!", icon:"none"});
								uni.redirectTo({
									url:'/pages/usercenter/usercenter'
								})
							}
						}).catch(err=>{
							console.log('request fail',err);
						})
					}
				}else{
					uni.showToast({ title: graceChecker.error, icon: "none" });
				}
			},
			//更换头像
			changetouxiang () {
				console.log(this.$refs.as)
				this.$refs.as.handleShow({
					actions: [
						  {
							name: '立即拍照',
							color: '#E02E24',
						  },
						  {
							name: '从相册选择',
							color: '#E02E24',
						  }
					],
					success: (res) => {
							switch (res.id) {
								// -1代表取消按钮
								case -1:
								  console.log(res)
								  break
								case 0:
								  console.log(res)
									this.camera ();
								  break
								case 1:
								  console.log(res);
									this.chooseImage();
								  break
							}
					}
				})
			},
			//拍照
			camera:function(){
				console.log('拍照');
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: (res) => {
						console.log('chooseImage success, temp path is', res.tempFilePaths[0])
						/* this.imageSrc=res.tempFilePaths; */
						var imageSrc = res.tempFilePaths[0]
						console.log(imageSrc)
						if (this.imageSrc.length < 1 ){
							this.imageSrc.push(imageSrc);
						}else{
							this.imageSrc.splice(0,1,imageSrc);
						}
					},
					fail: (err) => {
						console.log('chooseImage fail', err)
					}
				})
			},
			//选择图片
			chooseImage: function() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						console.log('chooseImage success, temp path is', res.tempFilePaths[0])
						/* this.imageSrc = res.tempFilePaths; */
						var imageSrc = res.tempFilePaths[0]
						console.log("1111111",imageSrc)
						if (this.imageSrc.length < 1 ){
							this.imageSrc.push(imageSrc);
						}else{
							this.imageSrc.splice(0,1,imageSrc);
						}
						
					},
					fail: (err) => {
						console.log('chooseImage fail', err)
					}
				})
			},
			//展示日期选择
			showbirthday(){
				this.mode='date';
				this.$refs[this.mode].show();
			},
			//选择日期
			onConfirmbirthday(val){
				console.log(val);
				this.birthdayValue=val.result;
			},
			//展示城市选择
			showcity(){
				this.mode='region';
				this.$refs[this.mode].show();
			},
			//选择城市
			onConfirmcity(val){
				console.log(val);
				this.cityValue=val.result;
			},
			//选择分类
			labelBtn(name,index){
			  console.log(name,index,"nameindex")
			  this.labelName = name
			  if(this.labelDataList.join(',').indexOf(name) >-1){
			    this.categorylist[index].checked = true
			  }else{
			    this.categorylist[index].checked = false
			  }
			},
			//添加选择分类结果
			checkboxChange: function (e) {
			  this.labelDataList = e.detail.value
			  console.log(e)
			  console.log('checkbox发生change事件，携带value值为：' + e.detail.value)
			  console.log(this.labelDataList,"labelDataList")
			},
		},
		// #ifndef MP
		onNavigationBarButtonTap() {
		},
		// #endif
		
	}
</script>

<style lang="scss">
	page {
			background: #f5f5f5;
			margin-bottom: 100upx;
	}
	.un-ti{
		width: 100%;
		background-color: #F5F5F5; 
		padding: 10upx;
		position: fixed;
		bottom: 0upx;
	}
	.btn-submit{
		background-color: #E02E24;
		margin: 0upx 38upx;
		
	}
	.un-touxiang{
		height: 270upx;
		background-color: #ffffff;
		text-align: center;
		.un-touxiang-text{
			font-size: 24upx;
			color:#999999 ;
		}
	}
	.portrait{
		width: 143upx;
		height: 143upx;
		border:5upx solid #fff;
		border-radius: 50%;
		margin-top:40upx;
	}
	
	.cu-form-group {
		background-color: #ffffff;
		padding: 1upx 50upx;
		display: flex;
		align-items: center;
		min-height: 83upx;
		justify-content: space-between;
	}
	.cu-form-group+.cu-form-group {
		border-top: 1upx solid #eee;
	}
	.cu-form-group .title {
		text-align: justify;
		font-size: 28upx;
		position: relative;
		height: 60upx;
		line-height: 60upx;
		min-width: calc(4em + 15px);
	}
	input{
		width: 550upx;
		font-size: 28upx;
		color: #999999;
	}
	.uni-flex {
		display: flex;
		flex-direction: row;
		margin-right: 237upx;
		font-size: 28upx;
	}
	
	.un-fentext{
		line-height: 100upx;
		font-size: 26upx;
		color: #999999;
		margin-left: 50upx;
	}
	.un-fenlei{
		background-color: #ffffff;
		height: 100%;
		width: 100%;
		border-top: 1upx solid #eee;
		border-button: 1upx solid #eee;
		padding: 30upx;
		.checkbox{
			border: 1upx solid #F2F2F2;
			border-radius: 52px;
			margin:10upx 25upx;
			color: #999999;
			font-size: 25upx;
			line-height: 60upx;
			text-align: center;
			width: 180upx;
		}
		.selectBox{
			background: #FFFFFF!important;
			color: #E02E24!important;
			border-color: #E02E24 !important;
		}
	}
	
	
</style>
